import 'package:graphql_flutter/graphql_flutter.dart';

import '../../config/token_storage.dart';
import '../graphql/user_gql.dart';

class AuthService {

  static Future<String> refreshToken(GraphQLClient client) async {
    final refreshToken = await TokenStorage.getRefreshToken();
    if (refreshToken == null) {
      throw Exception('No refresh token available');
    }

    final MutationOptions options = MutationOptions(
      document: gql(UserGQL.fetchRefreshToken),
      variables: {'refreshToken': refreshToken},
    );

    final QueryResult result = await client.mutate(options);

    if (result.hasException) {
      print("Error refreshing token: ${result.exception}");
      throw result.exception!;
    }

    final newAccessToken = result.data?['user']['refreshToken']['accessToken'] as String;
    final newRefreshToken = result.data?['user']['refreshToken']['refreshToken'] as String?;

    print("newAccessToken : $newAccessToken");
    print("newRefreshToken : $newRefreshToken");

    await TokenStorage.saveTokens(newAccessToken, newRefreshToken ?? refreshToken);
    return newAccessToken;
  }
}